import requests
import json

# 主账号用户名
MAIN_USER = "[填你自己的]"
# IAM 子账户用户名
IAM_USER = "[填你自己的]"

# IAM 子账户密码
IAM_PASSWORD = "[填你自己的]"

# 项目 ID
PROJECT_ID = "[填你自己的]"

# 服务器区域代号
SERVER_ID = "cn-north-4"

# 保存 TOKEN 的文件路径
TOKEN_FILE_PATH = "token.txt"

def get_token():
   """
   功能: 获取 TOKEN 并保存到本地文件
   """
   # 请求地址
   request_url = f"https://iam.{SERVER_ID}.myhuaweicloud.com/v3/auth/tokens"

   # 构造请求头
   headers = {
      "Content-Type": "application/json;charset=UTF-8"
   }

   # 构造请求体
   payload = {
      "auth": {
         "identity": {
            "methods": ["password"],
            "password": {
                "user": {
                   "domain": {
                      "name": MAIN_USER
                   },
                   "name": IAM_USER,
                   "password": IAM_PASSWORD
                }
            }
         },
         "scope": {
            "project": {
                "name": SERVER_ID
            }
         }
      }
   }

   # 发出 POST 请求
   try:
      response = requests.post(request_url, headers=headers, data=json.dumps(payload))

      # 打印状态码
      print(f"状态码: {response.status_code}")

      if response.status_code == 201:
         # 读取 X-Subject-Token 响应头
         token = response.headers.get("X-Subject-Token")

         # 打印返回的数据和 Token
         print(f"反馈的数据: {response.json()}")
         print(f"Token: {token}")

         # 保存 TOKEN 到本地文件
         if token:
            save_token_to_file(token)
            print(f"TOKEN 已保存到 {TOKEN_FILE_PATH}")
         else:
            print("未能获取到 TOKEN")
      else:
         print(f"获取 TOKEN 失败: {response.text}")

   except Exception as e:
      print(f"请求发生错误: {e}")

def save_token_to_file(token):
   """
   保存 TOKEN 到本地文件
   """
   try:
      with open(TOKEN_FILE_PATH, "w") as file:
         file.write(token)
   except Exception as e:
      print(f"保存 TOKEN 时发生错误: {e}")

def main():
   # 获取 TOKEN
   get_token()

if __name__ == "__main__":
   main()